﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Web.UI;
using System.Web.UI.WebControls;
using Module;

namespace HospitalManager.QuanTriHeThong.ThietLapHeThong
{
    public partial class Kho_Khoa : Page
    {
        private Module.QuanTriHeThong.ThietLapHeThong.Kho_Khoa _khoKhoa = new Module.QuanTriHeThong.ThietLapHeThong.Kho_Khoa();
        private readonly SelectAllClass _selectAllClass = new SelectAllClass();
        private int _totalrow;
        private const int PageSize = 20;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack) return;
            if (Session["username"] == null)
            {
                Response.RedirectToRoute("DangNhap");
            }
            else
            {
                LoadKhoa();
                LoadKho();
                LoadPage();
            }
        }

        protected void Page_PreRender(object sender, EventArgs e)
        {
            ViewState["CheckRefresh"] = Session["CheckRefresh"];
        }

        private void LoadKhoa()
        {
            ddlKhoa.DataSource = _selectAllClass.SelectAllKhoa();
            ddlKhoa.DataTextField = "TenKhoa";
            ddlKhoa.DataValueField = "MaKhoa";
            ddlKhoa.DataBind();
            ddlKhoa.Items.Insert(0, new ListItem("Chọn", ""));
        }

        private void LoadKho()
        {
            ddlKho.DataSource = _selectAllClass.SelectAllKho();
            ddlKho.DataTextField = "TenKho";
            ddlKho.DataValueField = "MaKho";
            ddlKho.DataBind();
        }

        private void LoadPage()
        {
            _khoKhoa = new Module.QuanTriHeThong.ThietLapHeThong.Kho_Khoa();
            gvDanhSach.DataSource = _khoKhoa.SelectAll(_khoKhoa, Convert.ToInt32(hfPageIndex.Value.Trim()), PageSize,
                out _totalrow);
            gvDanhSach.DataBind();
            GeneratePager(_totalrow, PageSize, Convert.ToInt32(hfPageIndex.Value.Trim()));
            Session["CheckRefresh"] = Server.UrlEncode(DateTime.Now.ToString(CultureInfo.InvariantCulture));
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            if (Session["username"] == null)
            {
                Response.RedirectToRoute("DangNhap");
            }
            else
            {
                if (Session["CheckRefresh"].ToString() == ViewState["CheckRefresh"].ToString())
                {
                    var str = _khoKhoa.DeleteById((((LinkButton)sender).CommandArgument).Trim())
                        ? "bootbox.alert('Xóa thành công!')"
                        : "bootbox.alert('Xóa thất bại!')";
                    ClientScript.RegisterClientScriptBlock(typeof(string), "alert", str, true);
                }
                ResetPage();
            }
        }

        protected void dlPager_ItemCommand(object source, DataListCommandEventArgs e)
        {
            if (e.CommandName != "PageNo") return;
            hfPageIndex.Value = e.CommandArgument.ToString();
            LoadPage();
            e.Item.Attributes.Add("disabled", "disabled");
        }

        public void GeneratePager(int totalRowCount, int pageSize, int currentPage)
        {
            const int totalLinkInPage = 4;
            var totalPageCount = (int)Math.Ceiling((decimal)totalRowCount / pageSize);

            var startPageLink = Math.Max(currentPage - (int)Math.Floor((decimal)totalLinkInPage / 2), 1);
            var lastPageLink = Math.Min(startPageLink + totalLinkInPage - 1, totalPageCount);

            if ((startPageLink + totalLinkInPage - 1) > totalPageCount)
            {
                lastPageLink = Math.Min(currentPage + (int)Math.Floor((decimal)totalLinkInPage / 2), totalPageCount);
                startPageLink = Math.Max(lastPageLink - totalLinkInPage + 1, 1);
            }

            var pageLinkContainer = new List<ListItem>();

            if (startPageLink != 1)
            {
                pageLinkContainer.Add(new ListItem("«", "1", currentPage != 1));
            }
            for (var i = startPageLink; i <= lastPageLink; i++)
            {
                pageLinkContainer.Add(new ListItem(i.ToString(CultureInfo.InvariantCulture),
                    i.ToString(CultureInfo.InvariantCulture), currentPage != i));
            }
            if (lastPageLink != totalPageCount)
                pageLinkContainer.Add(new ListItem("»", totalPageCount.ToString(CultureInfo.InvariantCulture),
                    currentPage != totalPageCount));

            dlPager.DataSource = pageLinkContainer;
            dlPager.DataBind();
        }

        protected void btnLuu_Click(object sender, EventArgs e)
        {
            if (Session["username"] == null)
            {
                Response.RedirectToRoute("DangNhap");
            }
            else
            {
                if (Session["CheckRefresh"].ToString() == ViewState["CheckRefresh"].ToString())
                {
                    var listkho = hfListKho.Value.Trim().Split(',');
                    foreach (var item in listkho)
                    {
                        _khoKhoa = new Module.QuanTriHeThong.ThietLapHeThong.Kho_Khoa
                        {
                            MaKhoa = ddlKhoa.SelectedValue.Trim(),
                            MaKho = item.Trim()
                        };
                        if (!_khoKhoa.Insert(_khoKhoa))
                        {
                            ClientScript.RegisterClientScriptBlock(typeof(string), "alert", "bootbox.alert('Cập nhật thất bại, vui lòng thử lại!')", true);
                        }
                    }
                }
                ResetPage();
            }
        }

        protected void btnNhaplai_Click(object sender, EventArgs e)
        {
            ResetPage();
        }

        private void ResetPage()
        {
            ddlKhoa.SelectedValue = "";
            hfListKho.Value = "";
            ddlKho.ClearSelection();
            LoadPage();
        }

        protected void gvDanhSach_OnRowDataBound(object sender, GridViewRowEventArgs e)
        {
            for (var i = gvDanhSach.Rows.Count - 1; i > 0; i--)
            {
                var row = gvDanhSach.Rows[i];
                var previousRow = gvDanhSach.Rows[i - 1];
                if (row.Cells[1].Text != previousRow.Cells[1].Text) continue;
                if (row.Cells[1].RowSpan == 0)
                {
                    previousRow.Cells[1].RowSpan = 2;
                }
                else
                {
                    previousRow.Cells[1].RowSpan = row.Cells[1].RowSpan + 1;
                }
                row.Cells[1].Visible = false;
            }
        }
    }
}